package com.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class LinwsRandomRule extends AbstractLoadBalancerRule {
    /*每个服务，访问5次 换下一个服务（3个）
     * total=0 默认=0 如果等于5 就指向下一个服务节点
     * index=0 默认为0 如果total=5 index+1
     * */
    private int total=0; //被调用的次数
    private int currentIndex=0; //当前是谁在提供服务
    @Override
    public Server choose(Object o) {
        return this.choose(this.getLoadBalancer(), o);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        super.initWithNiwsConfig(clientConfig);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig, Factory factory) {
        super.initWithNiwsConfig(clientConfig, factory);
    }
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();
                List<Server> allList = lb.getAllServers();
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }
//-----------------
                if (total<5){
                    server=upList.get(currentIndex);
                    total++;
                }else {
                    total=0;
                    currentIndex++;
                    if(currentIndex>upList.size()-1){
                        currentIndex=0;
                    }
                }
//-------------
//                int index = this.chooseRandomInt(serverCount);
//                server = (Server)upList.get(index);



                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }


}

